package cn.mystyle.service.user;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;

import cn.mystyle.common.bean.BaseResponse;
import cn.mystyle.common.constant.DefaultURI;
import cn.mystyle.common.constant.ResultCodeJson;
import cn.mystyle.common.http.ServiceClient;
import cn.mystyle.common.response.ListResponse;
import cn.mystyle.common.validate.RegularExpression;
import cn.mystyle.model.user.UserInfo;
import cn.mystyle.util.UserUtil;

/**
 * @author clark
 * 用户业务类
 */
@Service
public class UserService
{
    /**
     * 查询用户
     * @param request HTTP请求体
     * @param userParam 用户参数
     * @return String
     */
    public JSONObject login(HttpServletRequest request, UserInfo userParam)
    {
        // 调用用户原子服务
        ListResponse<UserInfo> result = ServiceClient.callList(userParam,
            DefaultURI.getUserURIKey(DefaultURI.URI_QUERY),
            UserInfo.getTypeReference());
        
        if (result.isSuccess())
        {
            if (!CollectionUtils.isEmpty(result.getResult()))
            {
                UserInfo userInfo = result.getResult().get(0);
                if (userInfo.getPassword().equals(userParam.getPassword()))
                {
                    // 不返回密码
                    userInfo.setPassword(null);
                    // 存放session
                    UserUtil.seesionLogin(request, userInfo);
                    
                    return ResultCodeJson.getSuccess(userInfo);
                }
            }
            
            // 返回账号与密码错误
            return ResultCodeJson.get6011001();
        }
        else
        {
            return JSONObject.parseObject(result.toString());
        }
    }
    
    /**
     * 注册用户并自动登录
     * @param request HTTP请求体
     * @param userParam 用户参数
     * @return String
     */
    public JSONObject signup(HttpServletRequest request, UserInfo userParam)
    {
        // 如果是手机
        if (userParam.getCombiField().matches(RegularExpression.REGEX_MOBILE))
        {
            userParam.setMobilePhone(userParam.getCombiField());
        }
        else
        {
            userParam.setEmail(userParam.getEmail());
        }
        // 清空
        userParam.setCombiField(null);
        
        // 调用用户原子服务
        BaseResponse result =
            ServiceClient.call(userParam, DefaultURI.getUserURIKey(DefaultURI.URI_ADD), BaseResponse.class);
        // 注册成功
        if (result.isSuccess())
        {
            // 自动登录
            return login(request, userParam);
        }
        else
        {
            // 注册失败返回错误
            return JSONObject.parseObject(result.toString());
        }
    }
    
}
